package handler

import (
	"context"
	"emicro_test/emicro_4/grpc_server/user/models"
	pb "emicro_test/emicro_4/grpc_server/user/pbfile"
	"emicro_test/emicro_4/grpc_server/user/common"
	"emicro_test/emicro_4/grpc_server/user/utils"
	"github.com/astaxie/beego/validation"
	"log"
	"time"
)


type UserHandler struct {
	service *common.EmicroService
}

func (u *UserHandler) TestUser(ctx context.Context, req *pb.TestReq, resp *pb.TestResp) error {
	log.Println(req.Id)
	resp.Msg = "user_id:" + utils.GetString(req.Id) + ", req:success"
	return nil
}

//注册
func (u *UserHandler) UserReg(ctx context.Context, req *pb.RegReq, resp *pb.RegResp) error {
	user := models.User{
		Name: req.Name,
		Phone: req.Phone,
		Email: req.Email,
		Pwd:req.Pwd,
		ConfirePwd:req.ConfirPwd,
		RegTime: time.Now().Unix(),
	}
	log.Printf("UserReg Params:%#v\n", user)

	//验证规则
	valid := validation.Validation{}
	b, err := valid.Valid(&user)
	if err !=nil{
		return err
	}
	if !b {
		for _, err := range valid.Errors {
			log.Println(err.Key, err.Message)
			resp.Status = common.RESP_ERROR
			resp.Msg = err.Message
			return nil
		}
	}

	//密码是否相等
	if req.Pwd != req.ConfirPwd{
		resp.Status = common.RESP_ERROR
		resp.Msg = "pwd not same"
		return nil
	}

	//手机号是否未被注册
	var count int64
	models.Db.Table("user").Where("phone = ?", req.Phone).Count(&count)
	if count > 0 {
		resp.Status = 2
		resp.Msg = "phone is exists"
		return nil
	}

	//邮箱是否未被注册
	models.Db.Table("user").Where("email = ?", req.Email).Count(&count)
	if count > 0 {
		resp.Status = 2
		resp.Msg = "email is exists"
		return nil
	}

	//写进数据库
	user.Pwd = utils.Md5(user.Pwd)

	result := models.Db.Create(&user)
	if result.Error != nil{
		return result.Error
	}

	resp.Status = common.RESP_SUCCESS
	resp.Msg = "success"

	return nil
}

//登录
func (u *UserHandler) UserLogin(ctx context.Context, req *pb.LoginReq, resp *pb.LoginResp) error{
	//验证规则
	valid := validation.Validation{}
	valid.Required(req.Phone, "phone")
	valid.Phone(req.Phone, "phone")
	valid.Required(req.Pwd, "pwd")
	valid.MinSize(req.Pwd, 4, "pwd")
	valid.MaxSize(req.Pwd, 6, "pwd")
	if valid.HasErrors() {
		for _, err := range valid.Errors {
			log.Println(err.Key, err.Message)
			resp.Status = common.RESP_ERROR
			resp.Msg = err.Message
			return nil
		}
	}

	//获取数据库信息
	type result struct {
		UserId int32
		Pwd string
	}

	var res result
	models.Db.Table("user").Select("user.user_id, user.pwd").Where("user.phone = ?", req.Phone).Scan(&res)
	if utils.Md5(req.Pwd) != res.Pwd {
		resp.Status = common.RESP_ERROR
		resp.Msg = "auth error"
		return nil
	}

	resp.Status = common.RESP_SUCCESS
	resp.UserId = utils.GetString(res.UserId)
	resp.Msg = "success"
	return nil

}

func NewUserHandler(service *common.EmicroService) *UserHandler{
	handler:= new(UserHandler)
	handler.service = service
	return handler
}
